package com.example.demo.controller;

import com.example.demo.bean.User;
import com.example.demo.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;

@Controller  //方便起见，这里就用themyleaf模板
@CrossOrigin
public class controller {
    //因为session存储在服务器上，服务器重启后，session就会消失，而cookie存储在浏览器，cookie还会在。
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/tologin")
    public String tologin(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        //因为session存储在服务器上，服务器重启后，session就会消失，而cookie存储在浏览器，cookie还会在。
        //如果服务器重启了，那么session不在必然会导致user空异常报错，所以用try,catch在cookie存在而session不存在的情况下抛出异常!
        //如果cookie被浏览器清除了，那么Cookie[]cookies=request.getCookies();也会报空值异常。
        try {
            Cookie[] cookies = request.getCookies();        //取到请求中的cookie
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("sessionid")) {
                    HttpSession session = request.getSession();

                    User user = (User) session.getAttribute(cookie.getValue()); //通过标识拿出存的user
                    response.getWriter().write("你的账号密码是" + user.getUsername() + "  " + user.getPassword());//测试用!

                    // 遍历session所有数据
                    System.out.println("开始遍历");
                    Enumeration<?> enumeration = session.getAttributeNames();
                    // 遍历enumeration
                    while (enumeration.hasMoreElements()) {
                        // 获取session的属性名称
                        String name = enumeration.nextElement().toString();
                        // 根据键值取session中的值
                        User user2 = (User) session.getAttribute(name);
                        // 打印结果
                        System.out.println("name:" + name + ",value:" + user2.toString());
                    }
                }
            }
        } catch (NullPointerException e) {
            response.getWriter().write("没有session/cookie信息,可能是服务器重启或者浏览器清除cookie导致");
        }
        return "login.html";
    }

    @RequestMapping("/login")
    public String login(String username, String password, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        User user = new User(username, password);
        int i = userMapper.login(user);
        if (i > 0) {
            //设置cookie
            Cookie cookie = new Cookie("sessionid", username);//标识为sessionid,内容为username
            cookie.setMaxAge(1000);
            response.addCookie(cookie);
            //设置session
            HttpSession session = request.getSession();
            session.setAttribute(username, user); //标识为username,数据存入user
            return "main.html";
        } else {
            return "login.html";
        }
    }

}
